#include "Topic.h"

#include "leveldb/options.h"
#include "leveldb/write_batch.h"
#include "db/write_batch_internal.h"

#include <iostream>

using namespace leveldb;

Topic::Topic(const std::string & name, const Options & options)
: _name(name)
, internal_comparator_(options.comparator)
{
}
Topic::~Topic(){
}

Status Topic::close(){
	if(mem_ != nullptr) mem_->Unref();
	if(imm_ != nullptr) imm_->Unref(); //TODO:
	return Status::OK();
}
Status Topic::open(){
	mem_ = new MemTable(internal_comparator_);
	mem_->Ref();
	return Status::OK();
}

Status Topic::put(const Slice & key, const Slice & value){
	WriteBatch batch;
	batch.Put(key, value);
	return write(&batch);
}

Status Topic::write(WriteBatch* updates){
	uint64_t last_sequence = getLastSequence();

	WriteBatchInternal::SetSequence(updates, last_sequence + 1);
	last_sequence += WriteBatchInternal::Count(updates);

	auto status = WriteBatchInternal::InsertInto(updates, mem_);
	if(status.ok()){
		setLastSequence(last_sequence);
	}
	return status;
}
Status Topic::get(const Slice & key, std::string & value){
	SequenceNumber snapshot = getLastSequence();	
	LookupKey lkey(key, snapshot);
	mem_->Ref();
	Status s ;
	if(mem_->Get(lkey, &value, &s)){
	}
	mem_->Unref();
	return s;
}
Status Topic::del(const Slice & key){
	WriteBatch batch;
	batch.Delete(key);
	return write(&batch);
}
